﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;

namespace IrisGenerator.Framework.UI.Controls
{
    public class BindableToolStripComboBox<T>:ToolStripComboBox,IBindableControl
    {
        public string TextDataMember { get; set; }

        #region IBaseControl Members

        public void LoadSource()
        {
            if (this.SourceMethod != null && !this.DesignMode)
                this.DataSource = GetDataSourceFromMethod();
            if (this.DataSource == null)
                return;

            IList source = this.DataSource as IList;
            if (source == null)
                return;

            if (string.IsNullOrEmpty(this.TextDataMember))
                return;

            foreach (T obj in source)
            {
                this.Items.Add(IrisGenerator.Framework.Reflection.Property.GetPropertyValue(obj, this.TextDataMember));
            }
        }

        public object DataSource { get; set; }

        private object GetDataSourceFromMethod()
        {
            bool result;
            try
            {
                object tmp = SourceMethod.Invoke(this, out result);
                return tmp;
            }
            catch
            {
                //HACK: Exception treatments.
                //throw;
                return null;
            }
            
        }




        public IrisGenerator.Framework.Reflection.MethodCall SourceMethod
        {
            get;set;
        }

        #endregion
    }
}
